<template>
  <div>
    <BasicModal
      width="80%"
      v-bind="$attrs"
      @register="registerModal"
      :title="getTitle"
      @ok="handleSubmit"
    >
      <BasicForm @register="registerForm">
        <template #localSearch="{ model, field }">
          <ApiSelect
            :api="GettitlelistApi"
            showSearch
            v-model:value="model[field]"
            optionFilterProp="label"
            resultField="data"
            labelField="title"
            valueField="randomId"
          />
        </template>
        <template #startTimechInput="{ model, field }">
          <a-input-group compact>
            <a-range-picker
              :show-time="{ format: 'HH:mm' }"
              v-model:value="dateValue"
              @panelChange="handlePanelChange"
              @change="handlePickerChange"
              :format="pickerFormat[dateType]"
              :valueFormat="pickerValueFormat[dateType]"
              :mode="pickerMode[dateType]"
              style="width: 70%"
            />
          </a-input-group>
        </template>

        <template #areaSearchInput="{ model, field }">
          <!-- <Select v-model:value="model[field]"
                  show-search
                  :allowClear="true"
                  :not-found-content="fetching ? undefined : null"
                  :filter-option="false"
                  @search="search"
                  @change="addressChange"
                  :options="addressOptions">
            <template v-if="fetching"
                      #notFoundContent>
              <Spin size="small" />
            </template>
          </Select>-->
          <div class="address-list">
            <Input
              v-model:value="model[field]"
              :allowClear="true"
              @blur="areaSearchBlur"
              class="address-item"
              @change="search"
            />
            <ul>
              <li
                v-for="item in addressOptions"
                :key="item.value"
                class="address-item"
                @click="addressChange(item.value)"
                >{{ item.label }}</li
              >
            </ul>
          </div>
        </template>
        <template #citySelect="{ model, field }">
          <Select
            :allowClear="true"
            v-model:value="model[field]"
            show-search
            :filter-option="false"
            @change="cityChangenew"
            :options="cityOptions"
          />
        </template>
        <template #areaSelect="{ model, field }">
          <Select
            :allowClear="true"
            v-model:value="model[field]"
            show-search
            :filter-option="false"
            @change="areaChange"
            :options="areaOptions"
          />
        </template>
        <template #areaSearch="{ model, field }">
          <ApiSelect
            :api="ListApi"
            class="selext"
            showSearch
            v-model:value="model[field]"
            optionFilterProp="label"
            resultField="list"
            labelField="name"
            valueField="id"
          />
        </template>
        <template #coverUrlSlot="{ model, field }">
          <Spin :spinning="spinning">
            <Upload
              class="uplod"
              v-model:file-list="fileList"
              name="file"
              list-type="picture-card"
              :show-upload-list="false"
              :action="uploadImgApi"
              :before-upload="beforeUpload"
              @change="handleChange"
            >
              <img v-if="model[field]" :src="model[field]" alt="avatar" />
              <div v-else>
                <div class="ant-upload-text">点击上传</div>
              </div>
            </Upload>
          </Spin>
          <div class="hint">建议图片尺寸：宽750*高440rpx</div>
        </template>
      </BasicForm>
      <Checkbox v-model:checked="checked" class="che1" @change="onOk"
        >为了活动的顺利发布，授权平台进行首图设计更换</Checkbox
      >
    </BasicModal>
  </div>
</template>
<script lang="ts">
  import moment, { Moment } from 'moment';
  import { computed, defineComponent, unref, reactive, ref, toRaw, h, onMounted } from 'vue';
  import { Select, Input, DatePicker, Spin, Upload } from 'ant-design-vue';
  moment.suppressDeprecationWarnings = true;
  const date = new Date();
  date.setMonth(0);
  date.setDate(1);
  date.setHours(0);
  date.setSeconds(0);
  date.setMinutes(0);
  const defultTimeValue = [moment(date), moment(new Date())];
  import { BasicForm, useForm, ApiSelect } from '/@/components/Form/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import {
    AddApi,
    EditApi,
    DetailsApiList,
    GettitlelistApi,
    GetcitylistApi,
    getfindCityAreaSchools,
  } from '/@/api/activityAdmin/index';
  import { UploadApi } from '/@/api/article/index';
  import { uploadVideoApi } from '/@/api/common/index';
  import { Checkbox, Input } from 'ant-design-vue';
  import { genderTypes, ADTypes, onlineStatusType2 } from '/@/assets/dic';
  import { FormSchema } from '/@/components/Table';
  // import { onlineStatus } from '/@/assets/dic';
  import { weeksOptions, Ioptions, schemas, IbusinessTime, FileItem, FileInfo } from './data';
  import { BasicUpload } from '/@/components/Upload';
  import { debounce } from 'lodash-es';
  import { useMessage } from '/@/hooks/web/useMessage';
  // import { getAppEnvConfig } from '/@/utils/env';
  import { convert, outputcents } from '/@/utils/throttle';
  import { SearchByKeyWordsApi, getAreaSiteApi } from '/@/api/common/index';
  import { getAppEnvConfig } from '/@/utils/env';
  export const formSchema: FormSchema[] = [
    {
      label: 'id',
      field: 'id',
      component: 'Input',
      show: false,
    },
    {
      label: 'province',
      field: 'province',
      component: 'Input',
      show: false,
    },
    {
      field: 'title',
      label: '活动标题:',
      component: 'Input',
      required: true,
      colProps: { lg: 24, md: 24 },
    },

    {
      field: 'mode',
      label: '活动方式:',
      component: 'Select',
      required: true,
      componentProps: {
        options: onlineStatusType2,
      },
      colProps: { lg: 24, md: 24 },
    },

    {
      label: '时间',
      field: 'startTime',
      component: 'RangePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        valueFormat: 'YYYY-MM-DD HH:mm',
        showTime: {
          format: 'HH:mm',
          defaultValue: [moment('00:00', 'HH:mm'), moment('00:00', 'HH:mm')],
        },
      },
      required: true,
      // slot: 'startTimechInput',
      colProps: { lg: 24, md: 24 },
    },

    {
      label: '区域位置',
      field: 'city',
      component: 'Input',
      rules: [
        {
          required: true,
          message: '请选择区域位置',
          trigger: 'change',
        },
      ],
      slot: 'citySelect',
      colProps: { span: 12 },
    },
    {
      label: '',
      field: 'area',
      labelWidth: 0,
      rules: [
        {
          required: true,
          message: '请选择区域位置',
          trigger: 'change',
        },
      ],
      component: 'Input',
      slot: 'areaSelect',
      colProps: { span: 12 },
    },

    {
      label: '详细地址',
      field: 'address',
      component: 'Input',
      slot: 'areaSearchInput',
      colProps: { lg: 24, md: 24 },
      rules: [
        {
          required: true,
          message: '请输入详细地址',
          trigger: 'blur',
        },
      ],
    },
    {
      field: 'remark',
      label: '详细描述:',
      component: 'InputTextArea',
      required: true,
      colProps: { lg: 24, md: 24 },
    },
    {
      label: '添加首图',
      field: 'coverUrl',
      component: 'Upload',
      slot: 'coverUrlSlot',
      colProps: { lg: 24, md: 24 },
      rules: [
        {
          required: true,
          validator: async (rule, value) => {
            if (!value) {
              /* eslint-disable-next-line */
              return Promise.reject('请添加首图');
            }
            return Promise.resolve();
          },
          trigger: 'change',
        },
      ],
    },
    {
      label: '添加图片',
      field: 'imgUrlsList',
      component: 'Upload',
      // component: 'UploadFile',
      colProps: { lg: 24, md: 24 },
      componentProps: {
        api: UploadApi,
        accept: ['jpg', 'jepg', 'png', 'JPG', 'PNG', 'JEPG', 'JPEG', 'jpeg'],
        maxNumber: 9,
        maxSize: 5,
      },
    },
    {
      label: '',
      field: 'authorize',
      component: 'Input',
      slot: 'authorizeInput',
      required: false,
      colProps: { lg: 24, md: 24 },
    },

    {
      label: '添加视频（选填）',
      field: 'videoUrl',
      component: 'Upload',
      // slot: 'uploadVideo',
      componentProps: {
        api: uploadVideoApi,
        maxNumber: 1,
        accept: ['mp4'],
        maxSize: 100,
      },
    },
    {
      label: '主办人简介',
      field: 'briefIntroduction',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: '主办人微信号',
      field: 'wechat',
      component: 'Input',
      required: true,
      colProps: { lg: 24, md: 24 },
    },
    {
      field: 'phone',
      label: '主办人电话:',
      component: 'Input',
      required: true,
      colProps: { lg: 24, md: 24 },
    },
    {
      field: 'symbol',
      label: '票价',
      component: 'Select',
      required: true,
      componentProps: {
        options: [
          {
            label: '$',
            value: '$',
            key: 0,
          },
          {
            label: '£',
            value: '£',
            key: 1,
          },
        ],
      },
      colProps: { xl: 7, md: 8 },
    },

    {
      field: 'prices',
      label: '',
      component: 'Input',
      required: true,
      colProps: { xl: 7, md: 8 },
      render: ({ model, field }) => {
        return h(Input, {
          placeholder: '请输入',
          value: model[field],
          onChange: (e: ChangeEvent) => {
            model[field] = e.target.value;
          },
          onBlur: (e: ChangeEvent) => {
            const value = e.target.value.replace(/,/g, '');
            model[field] = convert(value);
          },
        });
      },
    },
    {
      field: 'ticketUrl',
      label: '购票链接:',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
    },
    {
      field: 'registrationWay',
      label: '报名方式:',
      component: 'InputTextArea',
      componentProps: {
        maxLength: 100,
        showCount: true,
      },
      colProps: { lg: 24, md: 24 },
    },
  ];

  export default defineComponent({
    name: 'SalesUserModal',
    components: {
      Checkbox,
      BasicModal,
      BasicForm,
      ApiSelect,
      BasicUpload,
      Select,
      [Select.name]: Select,
      ASelectOption: Select.Option,
      [Input.name]: Input,
      [Input.Group.name]: Input.Group,
      [DatePicker.RangePicker.name]: DatePicker.RangePicker,
      Spin,
      Upload,
      Input,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      // 详情地址选择框
      const { createMessage } = useMessage();
      const mockData = ref({});
      const addressOptions = ref<Ioptions[]>([]);
      // 市区选择框
      const cityOptions = ref<Ioptions[]>([]);
      const fetching = ref<Boolean>(false);
      const addressClass = ref<String>('');
      // 区域选择框
      const mon = ref<number | string>();
      const areaOptions = ref<Ioptions[]>([]);
      const dateValue = ref<Moment[]>();
      const checked = ref(false);
      const dateType = ref<number>(2);
      const ckeType = ref<number>();
      const ctiyid = ref<number | string>();
      const cityName = ref<String>('');
      const pickerMode = reactive({
        0: ['year', 'year'],
        1: ['month', 'month'],
        2: ['date', 'date'],
      });

      const pickerFormat = reactive({
        0: 'YYYY',
        1: 'YYYY-MM',
        2: 'YYYY-MM-DD HH:mm',
      });

      const pickerValueFormat = reactive({
        0: 'YYYY',
        1: 'YYYY-MM',
        2: 'YYYY-MM-DD HH:mm',
      });
      // 图片APi
      const uploadImgApi = ref<string>(getAppEnvConfig().VITE_GLOB_API_URL + '/mini/getFileUrl');
      const spinning = ref<boolean>(false);
      const fileList = ref([]);
      const dateTimeStr = computed(() => {});
      // 详情地址
      function addressSearch(record: any) {
        fetching.value = true;
        addressOptions.value = [];
        if (record) {
          SearchByKeyWordsApi({ keyword: record, cityName: cityName.value })
            .then((res) => {
              res.data.map((items) => {
                let item = {
                  key: items.address,
                  label: items.address,
                  value: items.address,
                };
                addressOptions.value.push(item);
              });
              fetching.value = false;
            })
            .catch(() => {
              fetching.value = false;
            });
        }
      }

      function areaSearchBlur() {
        if (addressClass.value != 'address-item') {
          // nextTick(() => {
          // });
          setTimeout(() => {
            addressOptions.value = [];
          }, 200);
        }
      }
      onMounted(() => {
        document.addEventListener('click', dc);
      });
      const dc = (e: MouseEvent) => {
        addressClass.value = e.target.getAttribute('class');
      };
      const search = debounce((record: string) => {
        const address = getFieldsValue().address;
        addressSearch(address);
      }, 300);
      // 详情地址选择
      function addressChange(record: any) {
        if (record) {
          areaOptions.value = [];
          // cityOptions.value = [];
          addressOptions.value = [];
          setFieldsValue({ address: record });
          getAreaSiteApi({ address: record }).then((res: any) => {
            const { data } = res;
            setAreaOptions(data.area1, cityOptions.value, 'city');
            setAreaOptions(data.area2, areaOptions.value, 'area');
          });
        } else {
        }
      }
      // 区域地址
      function areaChange(record: String) {}
      // 城市地址
      function cityChange() {
        cityOptions.value = [];
        GetcitylistApi().then((res) => {
          res.data.map((items) => {
            const item: Ioptions = {
              key: items.id,
              label: items.city,
              value: items.id + '',
            };
            cityOptions.value.push(item);
          });
        });
      }
      cityChange();
      // 事件
      function cityChangenew(e) {
        if (e) {
          setFieldsValue({ area: '' });
          ctiyid.value = e;
          setCityName(e);
          areaOptions.value = [];
          const el = parseInt(e);
          getfindCityAreaSchools(el).then((res) => {
            res.data.area.map((items) => {
              let item = {
                key: items,
                label: items,
                value: items,
              };
              areaOptions.value.push(item);
            });
          });
        }
      }
      function setCityName(e: string) {
        const item = cityOptions.value.filter((item: Ioptions) => {
          return item.value == e;
        });
        if (item.length > 0) {
          cityName.value = item[0].label;
        }
        // cityName.value = item[0].label;
      }
      function setAreaOptions(data: any, options: Ioptions[], area: string) {
        if (Array.isArray(data)) {
          data.map((item) => {
            const ele: Ioptions = {
              key: item.id,
              label: item[area],
              value: item.id + '',
            };
            options.push(ele);
          });
          if (area == 'area' && !getFieldsValue().area) {
            let tmp: any[] = data.filter((item) => item.isShow === 1);
            if (tmp.length) {
              //值为1
              if (tmp[0].isShow == 1) {
                setFieldsValue({ area: tmp[0].id });
              }
            } else {
              //全部为0
              const ele: Ioptions = {
                key: '其他',
                label: '其他',
                value: '其他',
              };
              options.push(ele);
              setFieldsValue({ area: '其他' });
            }
          }
        } else if (data instanceof Object) {
          const ele: Ioptions = {
            key: data['id'],
            label: data[area],
            value: data['id'] + '',
          };
          const flag: Boolean = unref(options).some((item) => {
            return item.value == ele.value;
          });
          if (!flag) {
            options.push(ele);
          }
          if (area == 'city' && !getFieldsValue().area) {
            setFieldsValue({ [area]: data['id'] });
          }
        } else {
          const ele: Ioptions = {
            key: data,
            label: data,
            value: data + '',
          };
          options.push(ele);
          setFieldsValue({ area: data });
        }
      }
      // 处理地址格式
      emit('change', {
        type: toRaw(dateType.value),
        value: toRaw(dateTimeStr.value),
      });

      function handlePanelChange(val: Moment[], _: string[]) {
        console.log(val, 'val.value');
        dateValue.value = val;
        console.log(dateTimeStr.value, 'dateTimeStr.value');
        emit('change', {
          type: toRaw(dateType.value),
          value: toRaw(dateTimeStr.value),
        });
      }
      function handlePickerChange(val: Moment[], _: string[]) {
        console.log('dateTimeStr.value', val);
        dateValue.value = val;
        emit('change', {
          type: toRaw(dateType.value),
          value: toRaw(dateTimeStr.value),
        });
      }
      const onChange = (value, dateString) => {
        console.log('Selected Time: ', value);
        console.log('Formatted Selected Time: ', dateString);
      };
      const isUpdate = ref(true);
      const dataLsit = ref<any>([]);
      // 获取标题列表
      function getdataList() {
        GettitlelistApi({
          type: 0,
        }).then((res) => {
          dataLsit.value = res.data;
        });
      }
      getdataList();
      const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
        labelWidth: 160,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        addressOptions.value = [];
        cityName.value = '';
        resetFields();
        isUpdate.value = !!data?.isUpdate;
        mockData.value = {};
        if (data.record) {
          const detail = await DetailsApiList(data.record.id);
          if (detail.code == 200) {
            const { data } = detail;
            let keys: string[] = [
              'id',
              'title',
              'mode',
              'endTime',
              'startTime',
              'city',
              'area',
              'address',
              'remark',
              'coverUrl',
              'imgUrlsList',
              'authorize',
              'videoUrl',
              'briefIntroduction',
              'wechat',
              'phone',
              'symbol',
              'prices',
              'province',
              'ticketUrl',
              'registrationWay',
            ];
            const obj = {};
            for (const key of keys) {
              if (key == 'address') {
                // addressSearch(data[key]);
                addressChange(data[key]);
                obj[key] = data[key];
              } else if (key == 'mode' || key == 'city' || key == 'area') {
                obj[key] = data[key] + '';
              } else if (key == 'videoUrl' || key == 'imgUrlsList') {
                obj[key] = data[key] ? data[key] : [];
              } else if (key == 'startTime') {
                if (data[key] && data['endTime']) {
                  obj[key] = [moment(data[key] || ''), moment(data['endTime'])];
                }
              } else if (key == 'authorize') {
                checked.value = data[key];
              } else {
                obj[key] = data[key];
              }
            }
            if (obj['city']) {
              setTimeout(() => {
                setCityName(obj['city']);
              }, 1000);
              // cityId.value = obj['city'];
            }
            setFieldsValue(obj);
          }
          // mockData.value = { ...detail.data };
          // dateValue.value = [mockData._rawValue.startTime, mockData._rawValue.endTime];
          // data.record.city = add(mockData._rawValue.city);
          // checked.value = mockData._rawValue.authorize == 0 ? true : false;
          // data.record.mode = data.record.mode == 0 ? '0' : '1';
          // data.record.videoUrl = data.record.videoUrl ? [data.record.videoUrl] : [];
          // if (unref(isUpdate)) {
          //   if (data.record['city']) {
          //     cityName.value = data.record['city'];
          //   }
          //   setFieldsValue({
          //     ...data.record,
          //   });
          // }
        }
      });
      function add(cellValue) {
        switch (cellValue) {
          case 18:
            return '加州';
            break;
          case 19:
            return '加州';
            break;
          case 20:
            return '芝加哥地区';
            break;
          case 22:
            return '大纽约地区';
          case 23:
            return '大波士顿地区';
            break;
          case 51:
            return '康州';
            break;
          default:
            return '-';
            break;
        }
      }
      const getTitle = computed(() => (unref(isUpdate) ? '编辑活动' : '发布活动'));

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });
          const values = await validate();
          const getFields = await getFieldsValue();
          values.videoUrl = getFields.videoUrl ? getFields.videoUrl.toString() : '';
          values.authorize = ckeType.value;
          values.publisher = 1;
          values.isUse = 1;
          values.parentId = 0 | values.parentId;
          values.startTime = getFields.startTime[0];
          values.endTime = getFields.startTime[1];
          const item = cityOptions.value.filter((item) => {
            return item.value == values.city;
          });
          if (item.length > 0) {
            values.province = item[0].label;
          }
          // values.city = values.city
          //   ? mockData._rawValue.city
          //     ? ctiyid.value
          //     : values.city
          //   : ctiyid.value;
          if (values.id > 0) {
            await EditApi(values);
          } else {
            await AddApi(values);
          }
          values.city = [];
          resetFields();
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      const onOk = (e) => {
        if (e.target.checked == true) {
          ckeType.value = 0;
        } else {
          ckeType.value = 1;
        }
      };
      const handleChange = (info: FileInfo) => {
        if (info.file.status === 'uploading') {
          return;
        }
        if (info.file.status === 'done') {
          const { code, data } = info.file.response;
          if (code == 200) {
            setFieldsValue({ coverUrl: data[0] });
          }
        }
        if (info.file.status === 'error') {
          createMessage.error('上传失败！');
        }
        spinning.value = false;
      };
      const beforeUpload = (file: FileItem) => {
        spinning.value = true;
        const isJpgOrPng =
          file.type === 'image/jpeg' ||
          file.type === 'image/png' ||
          file.type === 'image/JPG' ||
          file.type === 'image/JEPG';
        if (!isJpgOrPng) {
          createMessage.error('上传图形格式只能上传：JPG、PNG、JPEG、JEPG!');
        }
        const isLt2M = file.size / 1024 / 1024 < 5;
        if (!isLt2M) {
          createMessage.error('图像必须小于5MB!');
        }
        return isJpgOrPng && isLt2M;
      };
      return {
        dateValue,
        dateType,
        ckeType,
        pickerFormat,
        addressSearch,
        addressChange,
        areaChange,
        cityOptions,
        cityChange,
        cityChangenew,
        areaOptions,
        addressOptions,
        pickerValueFormat,
        pickerMode,
        handlePanelChange,
        handlePickerChange,
        registerModal,
        registerForm,
        getTitle,
        handleSubmit,
        GettitlelistApi,
        onChange,
        onOk,
        checked,
        search,
        add,
        uploadImgApi,
        handleChange,
        beforeUpload,
        fileList,
        spinning,
        fetching,
        ctiyid,
        mon,
        areaSearchBlur,
      };
    },
  });
</script>
<style lang="less" scoped>
  .ant-spin-nested-loading {
    width: 104px;
  }
  :deep(.ant-upload) {
    margin: 0;
  }
  .ant-modal {
    position: relative;
  }
  .che1 {
    position: absolute;
    top: 100%;
    left: 11%;
  }
  @media screen and (max-width: 1746px) {
    .che1 {
      top: 117%;
      left: 12%;
    }
  }
  @media screen and (max-width: 1534px) {
    .che1 {
      top: 134%;
      left: 14%;
    }
  }
  @media screen and (min-height: 938px) and (max-height: 1100px) {
    .che1 {
      top: 96%;
    }
  }
  // @media screen and (max-width: 1299px) {
  //   .che1 {
  //     top: 13%;
  //   }
  // }
  // @media screen and (max-width: 986px) {
  //   .che1 {
  //     top: 22%;
  //   }
  // }
  :deep(.hint) {
    color: red;
  }
  .uplod {
    position: relative;
  }
  .address-list {
    position: relative;
    ul {
      width: 100%;
      position: absolute;
      top: 40px;
      left: 0;
      max-height: 300px;
      overflow-y: scroll;
      background: #fff;
      z-index: 99;
      li {
        padding-left: 5px;
        cursor: pointer;
        &:hover {
          background: #f5f5f5;
        }
      }
    }
  }
</style>
